//
//  DXDataPicker.m
//  express
//
//  Created by dd on 12/7/14.
//  Copyright (c) 2014 yunqi. All rights reserved.
//

#import "DXRegionPicker.h"
#import "DXUtil.h"
#import "DXLog.h"
#import "DXButton.h"

@implementation DXRegionPicker

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES;
        
        self.translatesAutoresizingMaskIntoConstraints = NO;
        self.autoresizesSubviews = NO;
        
        float screenWidth = [DX screenWidth];
        float screenHeight = [DX screenHeight];
        
        _pickerView = [[UIPickerView alloc] init];
        _pickerView.frame = CGRectMake(0, 40, screenWidth, _pickerView.frame.size.height);
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
        _pickerView.showsSelectionIndicator = YES;
        
        float totalHeight = _pickerView.frame.size.height + 40;
        
        self.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        
        _pickerHolder = [[UIView alloc] init];
        _pickerHolder.alpha = 0;
        _pickerHolder.backgroundColor = [DX colorWithHex:@"efefef"];
        _pickerHolder.frame = CGRectMake(0, screenHeight, screenWidth, totalHeight);
        
        UIView *line1 = [self makeLine:0];
        [_pickerHolder addSubview:line1];
        UIView *line2 = [self makeLine:39.5];
        [_pickerHolder addSubview:line2];
        
        DXButton *cancelBtn = [[DXButton alloc] initWithFrame:CGRectMake(10, 0, 80, 40)];
        [cancelBtn setTitle:@"取消" textColor:[DX colorWithHex:@"111111"] shadowColor:nil fontSize:16 bold:NO];
        [cancelBtn addTarget:self action:@selector(clickCancel:) forControlEvents:UIControlEventTouchUpInside];
        cancelBtn.realTitleLabel.textAlignment = NSTextAlignmentLeft;
        [_pickerHolder addSubview:cancelBtn];
        
        DXButton *doneBtn = [[DXButton alloc] initWithFrame:CGRectMake(screenWidth - 10 - 80, 0, 80, 40)];
        [doneBtn setTitle:@"确定" textColor:[DX colorWithHex:@"111111"] shadowColor:nil fontSize:16 bold:NO];
        [doneBtn addTarget:self action:@selector(clickOK:) forControlEvents:UIControlEventTouchUpInside];
        doneBtn.realTitleLabel.textAlignment = NSTextAlignmentRight;
        [_pickerHolder addSubview:doneBtn];
        
        [_pickerHolder addSubview:_pickerView];
        
        [self addSubview:_pickerHolder];
        
        
        // init data
        
        NSString *regionFile = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
        NSString *regionJsonString = [NSString stringWithContentsOfFile:regionFile encoding:NSUTF8StringEncoding error:nil];
        _region = [DX jsonDecode:regionJsonString];
        _provinceKeys = [_region.allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSString *key1 = obj1;
            NSString *key2 = obj2;
            if (key1.integerValue > key2.integerValue)
            {
                return NSOrderedDescending;
            }
            else if (key1.integerValue < key2.integerValue)
            {
                return NSOrderedAscending;
            }
            
            return NSOrderedSame;
        }];
    }
    
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)show
{
    _pickerHolder.alpha = 1;
    [_pickerView reloadAllComponents];
    
    NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
    UIScreen *mainScreen = UIScreen.mainScreen;
    
    for (UIWindow *window in frontToBackWindows)
    {
        if (window.screen == mainScreen && window.windowLevel == UIWindowLevelNormal)
        {
            [window addSubview:self];
            break;
        }
    }
    
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionAllowAnimatedContent
                     animations:^{
                         CGRect frame = _pickerHolder.frame;
                         frame.origin.y = [DX screenHeight] - _pickerHolder.frame.size.height;
                         _pickerHolder.frame = frame;
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

- (void)hide
{
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionAllowAnimatedContent
                     animations:^{
                         CGRect frame = _pickerHolder.frame;
                         frame.origin.y = [DX screenHeight];
                         _pickerHolder.frame = frame;
                     }
                     completion:^(BOOL finished) {
                         _pickerHolder.alpha = 0;
                         [self removeFromSuperview];
                     }];
}

- (UIView *)makeLine:(float)y
{
    float screenWidth = [DX screenWidth];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, y, screenWidth, 0.5)];
    line.backgroundColor = [DX colorWithHex:@"939393"];
    return line;
}

- (void)clickOK:(id)sender
{
    NSString *province = [self pickerView:_pickerView titleForRow:[_pickerView selectedRowInComponent:0] forComponent:0];
    NSString *city = [self pickerView:_pickerView titleForRow:[_pickerView selectedRowInComponent:1] forComponent:1];
    NSString *county = [self pickerView:_pickerView titleForRow:[_pickerView selectedRowInComponent:2] forComponent:2];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectProvince:city:county:)])
    {
        [self.delegate didSelectProvince:province city:city county:county];
    }
    
    [self hide];
}

- (void)clickCancel:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didCancelSelection)])
    {
        [self.delegate didCancelSelection];
    }
    
    [self hide];
}




- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            return _region.count;
        } break;
        case 1:
        {
            NSInteger provinceIndex = [_pickerView selectedRowInComponent:0];
            NSString *provineKey = _provinceKeys[provinceIndex];
            NSDictionary *province = _region[provineKey];
            NSDictionary *city = province[@"city"];
            return city.count;
        }
        case 2:
        {
            NSInteger provinceIndex = [_pickerView selectedRowInComponent:0];
            NSString *provineKey = _provinceKeys[provinceIndex];
            NSDictionary *province = _region[provineKey];
            NSDictionary *cityDict = province[@"city"];
            if (cityDict.count == 0) return 0;
            
            NSInteger cityIndex = [_pickerView selectedRowInComponent:1];
            NSString *cityKey = cityDict.allKeys[cityIndex];
            NSDictionary *city = cityDict[cityKey];
            NSDictionary *countyDict = city[@"county"];
            return countyDict.count;
        } break;
            
        default:
            break;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            NSString *provinceKey = _provinceKeys[row];
            NSDictionary *province = _region[provinceKey];
            return province[@"name"];
            
        } break;
        case 1:
        {
            NSInteger provinceIndex = [_pickerView selectedRowInComponent:0];
            NSString *provinceKey = _provinceKeys[provinceIndex];
            NSDictionary *province = _region[provinceKey];
            NSDictionary *cityDict = province[@"city"];
            if (cityDict.count == 0) return @"";
            
            NSString *cityKey = cityDict.allKeys[row];
            NSDictionary *city = cityDict[cityKey];
            return city[@"name"];
        }
        case 2:
        {
            NSInteger provinceIndex = [_pickerView selectedRowInComponent:0];
            NSString *provineKey = _provinceKeys[provinceIndex];
            NSDictionary *province = _region[provineKey];
            NSDictionary *cityDict = province[@"city"];
            if (cityDict.count == 0) return @"";
            
            NSInteger cityIndex = [_pickerView selectedRowInComponent:1];
            NSString *cityKey = cityDict.allKeys[cityIndex];
            NSDictionary *city = cityDict[cityKey];
            NSDictionary *countyDict = city[@"county"];
            if (countyDict.count == 0) return @"";
            
            NSString *countyKey = countyDict.allKeys[row];
            return countyDict[countyKey];
        } break;
            
        default:
            break;
    }
    return 0;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (view == nil) {
        view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, [DX screenWidth] / 3, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:view.frame];
        label.font = [UIFont systemFontOfSize:16];
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
    }
    
    UILabel *label = (UILabel*)view.subviews[0];
    label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    return view;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    if (component == 0)
    {
        [pickerView selectRow:0 inComponent:1 animated:NO];
        [pickerView selectRow:0 inComponent:2 animated:NO];
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
    }
    else if (component == 1)
    {
        [pickerView reloadComponent:2];
    }
}


@end
